package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private UserLocationApi userLocationApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;

    @Autowired
    private MessagesService messagesService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //查询今日佳人数据
    public TodayBest todayBest() {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.调用API查询
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        //默认显示(没人推荐)
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        //3.将RecommendUser转化为TodayBest对象
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        TodayBest vo = TodayBest.init(userInfo, recommendUser);
        return vo;
    }

    //查询分页推荐的好友列表（代码优化 用户信息只查询一遍就可以 不用反复调用API查询）
    public PageResult recommendation(RecommendUserDto dto) {
        Long userId = UserHolder.getUserId();
        //查询数据列表
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(), dto.getPagesize(), userId);
        //获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //判断列表是否为空
        if (items == null) {
            return pr;
        }
        //提取所有推荐的用户id列表
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        //构造查询条件 批量查询所有用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, userInfo);
        //循环推荐的数据列表，构建vo对象
        ArrayList<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if (info != null) {
                TodayBest vo = TodayBest.init(info, item);
                list.add(vo);
            }
        }
        //构造返回值
        pr.setItems(list);
        return pr;
    }

    //查看佳人详情
    public TodayBest personalInfo(Long userId) {
        //根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(userId);
        //根据操操作人id和被查看用户id查询两者的推荐数据
        RecommendUser user = recommendUserApi.queryByUserId(userId, UserHolder.getUserId());

        //改造：实现展示访客功能
        //构造访客数据，调用api保存
        Visitors visitors = new Visitors();
        visitors.setUserId(userId); //对方的id（去查看别人的详情）
        visitors.setVisitorUserId(UserHolder.getUserId());//当前操作人的id
        visitors.setFrom("首页");
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        visitors.setScore(user.getScore());
        visitorsApi.save(visitors);

        //构造返回值
        return TodayBest.init(userInfo, user);
    }

    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "对方还未设置陌生人问题" : question.getTxt();
    }

    //回复陌生人问题
    public void replyQuestion(Long userId, String reply) {
        //构造消息数据
        Long currentUserId = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findById(currentUserId);
        Map map = new HashMap();
        map.put("userId", currentUserId);
        map.put("huanXinId", "hx" + currentUserId); //固定用1380013800手机号用户测试
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        //转成JSON格式发送到环信服务器
        String message = JSON.toJSONString(map);
        //调用template对象，发送消息
        Boolean aBoolean = huanXinTemplate.sendMsg("hx" + userId, message);//1.接收方环信id 2.消息
        if (!aBoolean) {
            System.out.println("发送失败");
        }
    }

    //推荐用户列表 卡片
    public List<TodayBest> queryCardsList() {
        //调用api查询推荐数据列表(排除喜欢和不喜欢的用户，数量限制)
        List<RecommendUser> users = recommendUserApi.queryCardsList(UserHolder.getUserId(), 10);
        //判断数据是否存在
        if (CollUtil.isEmpty(users)) {
            //不存在推荐用户，随机构造推荐用户
            users = new ArrayList<>();
            String[] userIds = recommendUser.split(",");
            for (String userId : userIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(UserHolder.getUserId());
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                users.add(recommendUser);
            }
        }
        List<Long> userIds = CollUtil.getFieldValues(users, "userId", Long.class);
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(userIds, null);
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : users) {
            UserInfo userInfo = byIds.get(user.getUserId());
            if (userInfo != null) {
                TodayBest vo = TodayBest.init(userInfo, user);
                vos.add(vo);
            }
        }
        return vos;
    }

    //滑动卡片喜欢功能
    public void likeUser(Long likeUserId) {
        //保存喜欢数据（存入mongodb中）
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserId(), likeUserId, true);
        if (!save) {
            System.out.println("保存失败");
        }
        //操作redis，写入喜欢数据，删除不喜欢数据(喜欢的集合、不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + UserHolder.getUserId(), likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY + UserHolder.getUserId(), likeUserId.toString());
        //判断是否是双向喜欢
        if (isLike(likeUserId, UserHolder.getUserId())) {
            //双向喜欢添加好友
            messagesService.contacts(likeUserId);
        }
    }

    //判断是否有喜欢的方法
    public Boolean isLike(Long userId, Long likeUserId) {
        String key = Constants.USER_LIKE_KEY + userId;
        return redisTemplate.opsForSet().isMember(key, likeUserId.toString());
    }

    //不喜欢
    public void notLikeUser(Long likeUserId) {
        //保存喜欢数据（存入mongodb中）
        Boolean save = userLikeApi.saveOrUpdate(UserHolder.getUserId(), likeUserId, true);
        if (!save) {
            System.out.println("保存失败");
        }
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY + UserHolder.getUserId(), likeUserId.toString());
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + UserHolder.getUserId(), likeUserId.toString());
       /* if (isLike(likeUserId,UserHolder.getUserId())){
            //双向喜欢删除好友
        }*/
    }

    //搜附近的人
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //调用api查询附近用户（返回的是附近的人的id，当前用户id需要排除）
        List<Long> userIds = userLocationApi.queryNearUser(UserHolder.getUserId(), Double.valueOf(distance));
        //判断集合是否为空
        if (CollUtil.isEmpty(userIds)) {
            //空的话构造一个空的集合返回
            return new ArrayList<>();
        }
        //调用userInfoApi查询用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setGender(gender);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds,userInfo);
        List<NearUserVo> vos = new ArrayList<>();
        //构造返回值
        for (Long id :userIds){
            //排除当前用户id
            if (id == UserHolder.getUserId()) {
                continue;
            }
            UserInfo info = map.get(id);
            if (info != null) {
                NearUserVo vo = NearUserVo.init(info);
                vos.add(vo);
            }
        }
        return vos;
    }
}

   /* //查询分页推荐的好友列表(这种写法没有批量查询 会不断地查询用户信息 可能导致性能不好或阻塞)
    public PageResult recommendation(RecommendUserDto dto) {
        Long userId = UserHolder.getUserId();
        //查询数据列表
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(),dto.getPagesize(),userId);
        //获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //判断列表是否为空
        if (items == null) {
            return pr;
        }
        //循环RecommendUser数据列表，根据推荐的用户id查询用户详情
        ArrayList<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items){
            Long recommendUserId = item.getUserId();
            UserInfo userInfo = userInfoApi.findById(recommendUserId);
            if (userInfo!=null){
                if (!StringUtils.isEmpty(dto.getGender()) && !dto.getGender().equals(userInfo.getGender())){
                    continue;
                }
                if (dto.getAge()!=null && dto.getAge() < userInfo.getAge()){
                    continue;
                }
                TodayBest vo = TodayBest.init(userInfo, item);
                list.add(vo);
            }
        }
        //构造发回值
        pr.setItems(list);
        return pr;
    }*/
